<template>
  <el-dialog
    :title="displayStockName ? `${displayStockName} - 保本价格计算器` : '保本价格计算器'"
    :model-value="visible"
    width="100%"
    top="0"
    @close="handleClose"
    :z-index="2000"
    fullscreen
    custom-class="break-even-dialog"
  >
    <div class="break-even-calculator">
      <!-- 表单区域 -->
      <div class="form-section">
        <el-form :model="form" label-width="100px" class="break-even-form" inline>
          <el-form-item label="当前盈亏">
            <el-input-number
              v-model="form.currentProfitLoss"
              :precision="2"
              :step="0.01"
              :min="-99999999"
              :max="99999999"
              controls-position="right"
              size="small"
            />
            <span class="unit">元</span>
          </el-form-item>
          
          <el-form-item label="当前股价">
            <el-input-number
              v-model="form.currentPrice"
              :precision="3"
              :step="0.001"
              :min="0.001"
              :max="9999"
              controls-position="right"
              size="small"
            />
            <span class="unit">元</span>
          </el-form-item>
          
          <el-form-item label="持有股数">
            <el-input-number
              v-model="form.totalShares"
              :step="100"
              :min="0"
              :max="99999999"
              controls-position="right"
              size="small"
            />
            <span class="unit">股</span>
          </el-form-item>
          
          <el-form-item label="每上涨">
            <el-input-number
              v-model="form.priceIncrement"
              :step="0.001"
              :min="0.001"
              :max="1"
              :precision="3"
              controls-position="right"
              size="small"
            />
            <span class="unit">元卖出</span>
            <el-input-number
              v-model="form.sharesPerPoint"
              :step="100"
              :min="1"
              :max="99999999"
              controls-position="right"
              size="small"
              style="margin-left: 8px;"
            />
            <span class="unit">股</span>
          </el-form-item>
        </el-form>
      </div>
      
      <!-- 内容区域 -->
      <div class="content-section">
        <!-- 计算步骤展示 -->
        <div v-if="calculationSteps.length > 0" class="steps-container">
          <el-card class="steps-card" shadow="hover">
            <div slot="header" class="steps-header">
              <span><i class="el-icon-data-line"></i> 计算过程</span>
              <el-button type="text" size="small" @click="calculationSteps = []" style="float: right; color: #909399;">
                <i class="el-icon-delete"></i> 清空
              </el-button>
            </div>
            <div class="steps-content">
              <div class="calculation-list">
                <div v-for="(step, index) in pagedSteps" :key="index" class="calculation-item">
                  <div class="step-line">{{ step.content }}</div>
                </div>
              </div>
              <el-pagination
                v-if="calculationSteps.length > pageSize"
                @current-change="handlePageChange"
                :current-page="currentPage"
                :page-size="pageSize"
                :total="calculationSteps.length"
                layout="prev, pager, next"
                small
                style="margin-top: 8px; text-align: center;"
              />
            </div>
          </el-card>
        </div>

        <!-- 计算结果展示 -->
        <div v-if="result.breakEvenPrice !== null" class="result-container">
          <el-card class="result-card" shadow="hover">
            <div slot="header" class="result-header">
              <span><i class="el-icon-trophy"></i> 计算结果</span>
            </div>
            <div class="result-summary">
              <span class="result-summary-item">
                <span class="result-summary-label">保本价:</span>
                <span class="result-summary-value">{{ result.breakEvenPrice.toFixed(6) }}元</span>
              </span>
              <span class="result-summary-item">
                <span class="result-summary-label">卖出{{ result.sellCount }}次</span>
              </span>
              <span class="result-summary-item">
                <span class="result-summary-label">剩余{{ result.remainingShares }}股</span>
              </span>
              <span class="result-summary-item">
                <span class="result-summary-label">总额:</span>
                <span class="result-summary-value">{{ result.totalSellAmount.toFixed(2) }}元</span>
              </span>
              <span class="result-summary-item">
                <span class="result-summary-label">最终盈亏:</span>
                <span class="result-summary-value" :class="{ 'profit-positive': result.finalProfit >= 0, 'profit-negative': result.finalProfit < 0 }">
                  {{ result.finalProfit.toFixed(2) }}元
                </span>
              </span>
            </div>
          </el-card>
        </div>
      </div>

      <!-- 按钮区域 -->
      <div class="button-section">
        <el-button @click="handleClose" size="medium" round>
          <i class="el-icon-close"></i> 取消
        </el-button>
        <el-button type="primary" @click="calculateBreakEvenPrice" size="medium" round>
          <i class="el-icon-calculator"></i> 计算保本价
        </el-button>
        <el-button type="success" @click="useCurrentStockData" size="medium" round>
          <i class="el-icon-data-line"></i> 使用当前数据
        </el-button>
      </div>
    </div>
    

  </el-dialog>
</template>

<script>
export default {
  name: 'BreakEvenCalculator',
  props: {
    visible: {
      type: Boolean,
      default: false,
      required: true
    },
    currentStockData: {
      type: Object,
      default: () => ({})
    }
  },
  data() {
    return {
        form: {
          currentProfitLoss: 0,
          currentPrice: 0,
          totalShares: 0,
          sharesPerPoint: 2000,
          priceIncrement: 0.001
        },
        result: {
          breakEvenPrice: null,
          sellCount: 0,
          remainingShares: 0,
          totalSellAmount: 0,
          finalProfit: 0
        },
        calculationSteps: [],
        currentPage: 1,
        pageSize: 10,
        currentStockName: ''
      }
  },
  watch: {
    visible(newVal) {
      console.log('BreakEvenCalculator visible changed:', newVal)
      if (newVal) {
        // 当对话框显示时，自动加载当前数据
        console.log('自动加载当前数据...')
        this.$nextTick(() => {
          this.useCurrentStockData()
        })
      }
    },
    currentStockData: {
      handler(newVal) {
        console.log('currentStockData changed:', newVal)
        if (this.visible && newVal && Object.keys(newVal).length > 0) {
          this.useCurrentStockData()
        }
      },
      deep: true,
      immediate: true
    }
  },
  computed: {
    pagedSteps() {
      const start = (this.currentPage - 1) * this.pageSize
      const end = start + this.pageSize
      return this.calculationSteps.slice(start, end).map((step, index) => ({
        ...step,
        index: start + index
      }))
    },
    
    displayStockName() {
      if (this.currentStockName) {
        return this.currentStockName
      }
      if (this.currentStockData && this.currentStockData.stockName) {
        return this.currentStockData.stockName
      }
      if (this.currentStockData && this.currentStockData.stockCode) {
        return this.currentStockData.stockCode
      }
      return ''
    }
  },
  methods: {
    handleClose() {
      this.$emit('update:visible', false)
    },
    
    handlePageChange(page) {
      this.currentPage = page
    },
    
    resetForm() {
      this.form = {
        currentProfitLoss: 0,
        currentPrice: 0,
        totalShares: 0,
        sharesPerPoint: 2000,
        priceIncrement: 0.001
      }
      this.result = {
        breakEvenPrice: null,
        sellCount: 0,
        remainingShares: 0,
        totalSellAmount: 0,
        finalProfit: 0
      }
    },
    
    validateInput() {
      console.log('=== 开始输入验证 ===')
      console.log('验证输入数据:')
      console.log('- 持有股数:', this.form.totalShares)
      console.log('- 当前股价:', this.form.currentPrice)
      console.log('- 每上涨价格:', this.form.priceIncrement)
      console.log('- 每上涨价格卖出股数:', this.form.sharesPerPoint)
      
      if (this.form.totalShares <= 0) {
        console.log('验证失败: 持有股数必须大于0')
        this.$message.warning('请输入持有股数')
        return false
      }
      if (this.form.currentPrice <= 0) {
        console.log('验证失败: 当前股价必须大于0')
        this.$message.warning('请输入当前股价')
        return false
      }
      if (this.form.priceIncrement <= 0) {
        console.log('验证失败: 上涨价格必须大于0')
        this.$message.warning('请输入上涨价格')
        return false
      }
      if (this.form.sharesPerPoint <= 0) {
        console.log('验证失败: 每上涨价格卖出股数必须大于0')
        this.$message.warning('请输入每上涨价格卖出的股数')
        return false
      }
      
      console.log('输入验证通过')
      return true
    },
    
    calculateBreakEvenPrice() {
      // 清空之前的计算步骤
      this.calculationSteps = []
      
      const addStep = (title, content) => {
        this.calculationSteps.push({
          title,
          content,
          timestamp: new Date().toLocaleTimeString()
        })
      }
      
      addStep('开始计算', '开始计算保本价格...')
      
      if (!this.validateInput()) {
        addStep('验证失败', '输入验证失败，请检查输入数据')
        return
      }
      
      try {
        this.calculationSteps = []
        
        const addStep = (title, content) => {
          this.calculationSteps.push({
            title,
            content,
            timestamp: new Date().toLocaleTimeString()
          })
        }
        
        addStep('开始计算', `股数:${this.form.totalShares}股 | 价格:${this.form.currentPrice}元 | 盈亏:${this.form.currentProfitLoss}元 | 每上涨${this.form.priceIncrement}元卖${this.form.sharesPerPoint}股`)
        
        let currentShares = this.form.totalShares
        let currentPrice = this.form.currentPrice
        let currentProfit = this.form.currentProfitLoss
        let stepCount = 0
        
        // 循环计算，直到盈亏大于等于0
        while (currentProfit < 0 && currentShares > 0) {
          stepCount++
          
          // 价格上涨（使用用户设置的上涨幅度）
          currentPrice += this.form.priceIncrement
          
          // 计算本次卖出股数（使用用户设置的每上涨价格卖出股数）
          const sellShares = Math.min(this.form.sharesPerPoint, currentShares)
          
          // 本次收益 = 当前总股数 × 上涨的股价 - 卖出手续费1元
          const profitFromSell = currentShares * this.form.priceIncrement - 1
          
          // 更新盈亏
          currentProfit += profitFromSell
          
          // 更新股数
          currentShares -= sellShares
          
          addStep(`第${stepCount}步`, `价格:${currentPrice.toFixed(3)}元 | 卖出:${sellShares}股 | 收益:${profitFromSell.toFixed(2)}元(含1元手续费) | 盈亏:${currentProfit.toFixed(2)}元 | 剩余:${currentShares}股`)
          
          // 防止无限循环
          if (stepCount > 1000) {
            addStep('警告', '计算步数过多，停止计算')
            break
          }
        }
        
        // 最终结果
        if (currentProfit >= 0) {
          addStep('计算完成', `最终盈亏:${currentProfit.toFixed(2)}元≥0，达到保本目标！剩余:${currentShares}股`)
        } else {
          addStep('计算结束', `最终盈亏:${currentProfit.toFixed(2)}元<0，未能完全保本。剩余:${currentShares}股`)
        }
        
        this.result = {
          breakEvenPrice: currentPrice,
          sellCount: stepCount,
          remainingShares: currentShares,
          totalSellAmount: (this.form.totalShares - currentShares) * currentPrice,
          finalProfit: currentProfit
        }
        
        this.$message.success('保本价格计算完成')
      } catch (error) {
        addStep('错误', '计算失败: ' + error.message)
        this.$message.error('计算失败，请检查输入数据')
      }
    },
    
    useCurrentStockData() {
      console.log('=== 使用当前股票数据 ===')
      console.log('接收到的股票数据:', this.currentStockData)
      console.log('当前对话框可见状态:', this.visible)
      
      if (this.currentStockData && Object.keys(this.currentStockData).length > 0) {
        console.log('开始填充数据:')
        console.log('- 股票名称:', this.currentStockData.stockName)
        console.log('- 股票代码:', this.currentStockData.stockCode)
        console.log('- 当前股价:', this.currentStockData.currentPrice)
        console.log('- 总股数:', this.currentStockData.totalShares)
        console.log('- 盈亏:', this.currentStockData.profitLoss)
        
        // 设置股票名称
        this.currentStockName = this.currentStockData.stockName || this.currentStockData.stockCode || ''
        
        this.form.currentPrice = this.currentStockData.currentPrice || 0
        this.form.totalShares = this.currentStockData.totalShares || 0
        this.form.currentProfitLoss = this.currentStockData.profitLoss || 0
        
        console.log('填充完成:')
        console.log('- 股票名称:', this.currentStockName)
        console.log('- 表单当前股价:', this.form.currentPrice)
        console.log('- 表单总股数:', this.form.totalShares)
        console.log('- 表单盈亏:', this.form.currentProfitLoss)
        console.log('- 表单每上涨卖出股数:', this.form.sharesPerPoint)
        console.log('- 表单每上涨价格:', this.form.priceIncrement)
        
        this.$message.success(`已填充 ${this.currentStockName} 的当前数据`)
      } else {
        console.log('暂无当前股票数据')
        this.$message.warning('暂无当前股票数据')
      }
      console.log('=== 填充完成 ===')
    }
  }
}
</script>

<style scoped>
/* 修复 el-dialog 全屏模式下的高度问题 */
:deep(.el-dialog__body) {
  padding: 0 !important;
  height: calc(100vh - 54px) !important; /* el-dialog header 高度约为 54px */
  overflow: hidden !important;
  display: flex !important;
  flex-direction: column !important;
}

.break-even-calculator {
 
  background: #ffffff;
  display: flex;
  flex-direction: column;
  overflow: hidden;
  position: relative;
}

/* 表单区域 - 固定高度 */
.form-section {
  flex: 0 0 auto;
  padding: 10px 20px;
  border-bottom: 1px solid #f0f0f0;
  max-height: 160px; /* 减小表单区高度 */
  overflow: hidden;
}

/* 内容区域 - 自适应高度 */
.content-section {
  flex: 1 1 auto;
  overflow-y: auto; /* 启用滚动条 */
  padding: 12px 20px;
  min-height: 0; /* 重要：防止flex项目溢出 */
  display: flex;
  flex-direction: column;
  max-height: calc(100vh - 54px - 160px - 44px); /* 减小表单区高度，增加内容区域 */
}
  
  .break-even-form {
  margin: 0 auto;
  width: 100%;
  background: #ffffff;
  padding: 12px 20px;
  border-radius: 8px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

/* 表单样式优化 */
.break-even-form .el-form-item {
  margin-bottom: 6px;
  margin-right: 20px;
}

.break-even-form .el-form-item__label {
  font-weight: 500;
  color: #333;
  font-size: 16px;
}

.break-even-form .el-input-number {
  width: 140px;
}

.break-even-form .el-input__inner {
  border-radius: 4px;
  border: 1px solid #d9d9d9;
  transition: all 0.3s ease;
}

.break-even-form .el-input__inner:focus {
  border-color: #1890ff;
  box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.2);
}

.break-even-form .unit {
  margin-left: 10px;
  color: #666;
  font-size: 14px;
  font-weight: 400;
}

.result-container {
    margin: 6px 0;
    padding: 6px;
    background: #f8f9fa;
    border-radius: 8px;
    border: 1px solid #d1ecf1;
    flex: 0 0 auto; /* 固定高度，让计算结果区域更紧凑 */
  }
  
  .result-card {
    background: #ffffff;
    border: 1px solid #e0e0e0;
    border-radius: 8px;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
    overflow: hidden;
  }
  
  .result-header {
    font-weight: 600;
    color: #2c3e50;
    padding: 4px 0;
    font-size: 14px;
    border-bottom: 1px solid #e0e0e0;
    margin-bottom: 2px;
    display: flex;
    align-items: center;
    gap: 4px;
  }

/* 计算步骤样式 */
  .steps-container {
    margin: 8px 0;
    flex: 2 1 auto; /* 增加占比，让计算过程区域更大 */
    display: flex;
    flex-direction: column;
    min-height: 300px; /* 增加最小高度 */
    max-height: none; /* 移除最大高度限制，全屏展示 */
    overflow: hidden;
  }
  
  .steps-card {
    background: #ffffff;
    border: 1px solid #e0e0e0;
    border-radius: 6px;
    box-shadow: 0 1px 4px rgba(0, 0, 0, 0.1);
    flex: 1;
    display: flex;
    flex-direction: column;
    min-height: 0;
  }
  
  .steps-header {
    font-weight: 600;
    color: #2c3e50;
    padding: 8px 0;
    font-size: 16px;
    border-bottom: 1px solid #e0e0e0;
    margin-bottom: 6px;
    display: flex;
    align-items: center;
    gap: 6px;
  }
  
  .steps-content {
    flex: 1;
    overflow-y: auto; /* 允许步骤内容滚动 */
    padding: 10px 20px;
    max-height: none; /* 移除最大高度限制，全屏展示 */
  }
  
  .calculation-list {
    padding: 6px 0;
  }
  
  .calculation-item {
    padding: 6px 12px;
    border-bottom: 1px solid #f0f0f0;
    background: #ffffff;
    font-size: 13px;
    line-height: 1.4;
    display: flex;
    align-items: center;
    min-height: 24px;
  }
  
  .calculation-item:last-child {
    border-bottom: none;
  }
  
  .calculation-item:last-child {
    border-bottom: none;
  }
  
  .step-line {
    color: #333;
    font-size: 13px;
    line-height: 1.3;
    font-weight: 400;
  }
  
  .step-content li {
    margin: 2px 0;
  }
  
  .el-table::before {
    height: 0;
  }
  
  .el-table .el-table__row:hover {
    background-color: #f5f5f5;
  }

.dialog-footer {
    text-align: center;
    padding: 15px 20px;
    background: #ffffff;
    border-top: 1px solid #e0e0e0;
  }

/* 按钮区域样式 */
.button-section {
  flex: 0 0 auto;
  padding: 8px 15px;
  text-align: center;
  background: #ffffff;
  border-top: 1px solid #e4e7ed;
  display: flex;
  justify-content: center;
  gap: 8px;
  height: 44px;
}

.result-item {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 8px;
    font-size: 14px;
    padding: 4px 0;
    border-bottom: 1px solid #f0f0f0;
  }

.result-item:last-child {
  margin-bottom: 0;
  border-bottom: none;
}

.result-label {
  color: #333;
  font-weight: 500;
  font-size: 14px;
}

.result-value {
  color: #1890ff;
  font-weight: 600;
  font-size: 16px;
}

/* 单行显示的计算结果样式 */
.result-summary {
  display: flex;
  justify-content: space-around;
  align-items: center;
  padding: 6px 0;
  gap: 12px;
}

.result-summary-item {
  display: flex;
  align-items: center;
  gap: 3px;
  white-space: nowrap;
}

.result-summary-label {
  color: #666;
  font-size: 13px;
  font-weight: 400;
}

.result-summary-value {
  color: #1890ff;
  font-size: 14px;
  font-weight: 600;
}

/* 盈亏样式 */
.profit-positive {
  color: #52c41a !important;
}

.profit-negative {
  color: #ff4757 !important;
}

@media (max-width: 768px) {
  .break-even-form {
    padding: 0 10px;
  }
  
  .result-item {
    flex-direction: column;
    align-items: flex-start;
    gap: 5px;
  }
  
  .result-label,
  .result-value {
    font-size: 14px;
  }
}
</style>